import React from 'react';
import {View, ScrollView, TouchableOpacity, Image, Text, FlatList, Platform, RefreshControl} from 'react-native';
import Swiper from 'react-native-swiper';
import {Ticon} from 'react-native-ticon';
import {CacheImage} from 'react-native-dsx-cache-image';
import {LoadingView} from "react-native-dsxui";
import {Colors, Size, Styles} from '../../styles';
import {ApiClient} from "../../utils";
import {SearchBar} from "../../components";
import Menus from '../../base/menus';
import {connect} from "react-redux";

class HomeIndex extends React.Component {

    static navigationOptions = ({navigation}) => ({
        header: (
            <View style={{
                backgroundColor: '#fff',
                height: Platform.OS === 'ios' ? 64 : 44,
                paddingTop: Platform.OS === 'ios' ? 30 : 10
            }}>
                <View style={{flexDirection: 'row', paddingLeft: 15, paddingRight: 15, height: 30}}>
                    <View style={{
                        marginRight: 20,
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <Ticon name={"scan-light"}
                               size={28}
                               color={Colors.headerTintColor}
                               style={{marginTop: 1}}
                               onPress={() => {
                                   navigation.navigate('QRScanner');
                               }}/>
                    </View>
                    <SearchBar
                        barStyle={{flex: 1}}
                        placeholderTextColor={"#666"}
                        editable={false}
                        onPress={() => {
                            navigation.navigate('SearchView');
                        }}
                        placeholder={"请输入关键字"}
                    />
                    <View style={{
                        marginLeft: 20,
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}>
                        <Ticon
                            name={"more-light"}
                            size={28}
                            color={Colors.headerTintColor}
                            onPress={() => navigation.navigate('FeedIndex')}
                        />
                    </View>
                </View>
            </View>
        )
    });

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            isRefreshing: false,
            images: [],
            courses: []
        };
    }


    render(): React.ReactNode {
        if (this.state.isLoading) return <LoadingView/>;
        return (
            <ScrollView
                refreshControl={<RefreshControl refreshing={this.state.isRefreshing} onRefresh={this.refresh}/>}
                style={{
                    backgroundColor: '#fff',
                    paddingLeft: 15,
                    paddingRight: 15,
                    paddingTop: 15,
                    flex: 1
                }}
            >
                {this.renderSwiper()}
                <View style={{
                    paddingTop: 15,
                    paddingBottom: 15,
                    marginTop: 15
                }}>
                    <Text style={{
                        fontSize: 22,
                        fontWeight: '500',
                        color: '#000'
                    }}>最新课程</Text>
                </View>
                {this.renderCourses()}
            </ScrollView>
        );
    }

    componentDidMount(): void {
        this.fetchData();
    }

    fetchData = async () => {
        let response = await ApiClient.get('/block/item/batchget', {block_id: 1});
        const images = response.data.items;

        response = await ApiClient.get('/course/batchget', {count: 5});
        const courses = response.data.items;
        console.log(courses);

        this.setState({
            images,
            courses,
            isLoading: false,
            isRefreshing: false
        });
    };

    refresh = () => {
        this.setState({isRefreshing: true}, () => this.fetchData());
    };

    renderSwiper = () => {
        const size = {
            width: Size.screenWidth - 30,
            height: Size.screenWidth * 0.4
        };
        let contents = this.state.images.map((item, index) => {
            return (
                <TouchableOpacity
                    activeOpacity={1}
                    key={'key1' + index.toString()}
                    onPress={() => {
                        if (/http(.*?)\/post\/detail\/(\d+)\.html/.test(item.url)) {
                            let aid = item.url.match(/(\d+)/g)[0];
                            this.props.navigation.navigate('PostDetail', {aid});
                        }
                    }}
                >
                    <CacheImage
                        source={{uri: item.image}}
                        style={{
                            ...size,
                            borderRadius: 10,
                            resizeMode: 'stretch'
                        }}
                    />
                </TouchableOpacity>
            );
        });

        return (<Swiper style={{height: size.height, borderRadius: 10}} dotColor={"#ccc"} autoplay>{contents}</Swiper>);
    };

    renderMenus = () => {
        let contents = Menus.map((menu, index) => {
            return (
                <TouchableOpacity
                    activeOpacity={1}
                    style={{
                        alignContent: 'center',
                        alignItems: 'center',
                        width: Size.screenWidth * 0.25,
                        marginTop: 8,
                        marginBottom: 8
                    }}
                    onPress={() => {
                        this.props.navigation.navigate(menu.url, menu.params);
                    }}
                    key={'key2' + index.toString()}
                >
                    <Image
                        source={menu.icon}
                        style={{
                            width: 50,
                            height: 50
                        }}
                    />
                    <Text style={{
                        fontSize: 14,
                        color: '#333',
                        textAlign: 'center',
                        marginTop: 5
                    }}>{menu.title}</Text>
                </TouchableOpacity>
            );
        });

        return (
            <View style={{
                paddingTop: 10,
                paddingBottom: 10,
                flexDirection: 'row',
                flexWrap: 'wrap',
                backgroundColor: '#fff'
            }}>{contents}</View>
        );
    };

    renderCourses = () => {
        return (
            <FlatList
                keyExtractor={(item) => item.id.toString()}
                data={this.state.courses}
                renderItem={({item}) => {
                    return (
                        <TouchableOpacity
                            activeOpacity={0.9}
                            style={{
                                borderBottomColor: '#e5e5e5',
                                borderBottomWidth: 0.5,
                                flexDirection: 'row',
                                backgroundColor: '#fff',
                                paddingTop: 15,
                                paddingBottom: 15
                            }}
                            onPress={() => this.props.navigation.navigate('CourseDetail', {course_id: item.id})}
                        >
                            {
                                item.image ?
                                    <CacheImage
                                        source={{uri: item.image}}
                                        style={{
                                            width: 120,
                                            height: 90,
                                            borderRadius: 3,
                                            resizeMode: 'cover',
                                            marginRight: 15
                                        }}
                                    />
                                    : null
                            }
                            <View style={{flex: 1, paddingTop: 5}}>
                                <Text
                                    style={{fontSize: 18, fontWeight: '500', color: '#000'}}
                                    numberOfLines={2}
                                >{item.title}</Text>
                                <Text style={{fontSize: 14, color: '#666', marginTop: 10}}>已有{item.sold}人购买学习</Text>
                                {
                                    item.price > 0 ?
                                        <View style={{flexDirection: 'row', marginTop: 10}}>
                                            <Text style={{fontSize: 14, color: '#666'}}>学习价格</Text>
                                            <Text style={{fontSize: 14, color: '#f40', fontWeight: '600'}}>{item.price}元</Text>
                                        </View>
                                        :
                                        <Text style={{fontSize: 14, color: '#f40', marginTop:10}}>免费学习</Text>
                                }
                            </View>
                        </TouchableOpacity>
                    );
                }}
            />
        );
    };
}

const mapStateToProps = (store) => {
    return {
        auth: store.auth
    };
};

export default connect(mapStateToProps)(HomeIndex);
